package com.xc.erp.modules.erp.controller;

import com.xc.erp.common.annotation.Log;
import com.xc.erp.common.constants.ExceptionConstants;
import com.xc.erp.common.utils.SecurityUtils;
import com.xc.erp.modules.erp.domain.AjaxResult;
import com.xc.erp.modules.erp.domain.dto.LoginBody;
import com.xc.erp.modules.erp.domain.dto.LoginUser;
import com.xc.erp.modules.erp.domain.pojo.JshFunction;
import com.xc.erp.modules.erp.domain.pojo.JshUser;
import com.xc.erp.modules.erp.service.JshFunctionService;
import com.xc.erp.modules.erp.service.JshUserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 登录接口
 *
 * @author wjw 2022/11/22
 * @DateTime: 2022/11/22 17:12
 */
@RestController
public class LoginController {

    @Autowired
    private JshUserService jshUserService;

    @Autowired
    private JshFunctionService jshFunctionService;

    @Log(modul = "用户",desc = "登录日志")
    @PostMapping("/user/login")
    public AjaxResult login(@RequestBody LoginBody loginBody){
        return jshUserService.login(loginBody);
    }

    @GetMapping("/user/info")
    public AjaxResult info(){
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        return AjaxResult.success()
                .put("user",loginUser.getJshUser())
                .put("roles","admin")
                .put("permissions",loginUser.getPerms());
    }

    @GetMapping("/function/getRouters")
    public AjaxResult getRouters(){
        Long userId = SecurityUtils.getUserId();
        List<JshFunction> functionList = jshFunctionService.selectMenuById(userId);
        return AjaxResult.success(jshFunctionService.buildMenus(functionList));
    }

    @Log(modul = "用户",desc = "登出")
    @PostMapping("/user/logout")
    public Object logout(){
        return jshUserService.logout();
    }

    @ApiOperation("注册接口")
    @PostMapping("/user/register")
    public AjaxResult register(@RequestBody JshUser jshUser){
        if (jshUserService.saveJshUser(jshUser)){
            return AjaxResult.success();
        } else {
            return AjaxResult.error(ExceptionConstants.USER_ADD_FAILED_CODE,ExceptionConstants.USER_ADD_FAILED_MSG);
        }
    }
}
